package org.dromara.bean.service.impl;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.bean.constant.CommonCode;
import org.dromara.bean.domain.HisRegion;
import org.dromara.bean.domain.model.HisRegionModel;
import org.dromara.bean.mapper.BaseRegionMapper;
import org.dromara.bean.service.IBaseRegionService;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Description: 地区表
 * @Author: jeecg-boot
 * @Date: 2020-04-27
 * @Version: V1.0
 */
@Service
@RequiredArgsConstructor
public class BaseRegionServiceImpl extends ServiceImpl<BaseRegionMapper, HisRegion> implements IBaseRegionService {


    private final BaseRegionMapper appRegionMapper;

    /**
     * 查询地区列表
     *
     * @param flag
     * @return
     */
    @Override
    public List<HisRegion> getAppRegionList(String flag) {
        return appRegionMapper.getSysRegionList(flag);
    }

    /**
     * 查询热门城市列表
     *
     * @param flag
     * @param is_hot
     * @return
     */
    @Override
    public List<HisRegionModel> getIsHotList(String flag, String is_hot) {
        return appRegionMapper.getIsHotList(flag, is_hot);
    }

    /**
     * 查询所有数据
     *
     * @param page
     * @return
     */
    @Override
    public List<HisRegion> getAllRegionList(Page<HisRegion> page, String flag) {
        return appRegionMapper.getAllRegionList(page, flag);
    }

    @Override
    public List<HisRegion> getRegionListByRegExp(List<HisRegion> listAll, String regex) {
        if (listAll == null || (listAll.size() == 0)) {
            return null;
        }

        List<HisRegion> listResult = new ArrayList<HisRegion>();
        Pattern pattern = Pattern.compile(regex);

        for (HisRegion appRegion : listAll) {
            if (pattern.matcher(String.valueOf(appRegion.getRegionCode())).matches()) {
                listResult.add(appRegion);
            }
        }
        return listResult;
    }

    @Override
    public List<HisRegionModel> listAll() {
        return appRegionMapper.selectAll();
    }

    @Override
    public List<HisRegionModel> provinceAll() {
        return appRegionMapper.selectProvinceAll();
    }

    @Override
    public List<HisRegionModel> cityOrArea(Integer pid, String region) {
        return appRegionMapper.selectCityOrArea(pid, region);
    }

    @Override
    public String getAddressByRegionId(Integer regionId) {
        return appRegionMapper.selectAddressByRegionId(regionId);
    }

    @Override
    public R<?> queryPageList(Integer pageNo, Integer pageSize, String regionCode, String flag) {
        Page<HisRegion> page = new Page<HisRegion>(pageNo, pageSize);
        // 加载省、市、县区
        List<HisRegion> listAll = null;
        List<HisRegion> regionsAll = null;
        try {
            if ("province".equals(flag)) {
                listAll = this.getAllRegionList(page, flag);
            } else {
                listAll = this.getAppRegionList(flag);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        if ("province".equals(flag)) {
            regionsAll = this.getRegionListByRegExp(listAll, "^[0-9][1-9]0000$");
        } else if ("city".equals(flag)) {
            if (!(StringUtils.isEmpty(regionCode)) && (regionCode.length() == 6)) {
                regionCode = regionCode.substring(0, 2);
            }
            regionsAll = this.getRegionListByRegExp(listAll, "^" + regionCode + "[0-9][1-9]00$");
        } else if ("area".equals(flag)) {
            if (!(StringUtils.isEmpty(regionCode)) && (regionCode.length() == 6)) {
                regionCode = regionCode.substring(0, 4);
            }
            regionsAll = this.getRegionListByRegExp(listAll, "^" + regionCode + "[0-9][1-9]$");
        }
        return R.ok(regionsAll);
    }

    @Override
    public R<?> isHostList() {

        String flag = "city";
        String is_hot = "1";
        List<HisRegionModel> isHosList = null;
        try {
            isHosList = this.getIsHotList(flag, is_hot);
        } catch (Exception e) {
            e.getMessage();
            return R.errorCode(CommonCode.ENTITY_NULL_ERROR);
        }
        return R.ok(isHosList);
    }

    @Override
    public R<?> queryList() {
        List<HisRegionModel> citys = this.listAll();
        //过滤掉顶级中国
        List<HisRegionModel> cityList = citys.stream().filter(e -> !"中国".equals(e.getTitle()) && !e.equals(null)).collect(Collectors.toList());

        List<HisRegionModel> baseTreeList = new ArrayList<>();
        List<HisRegionModel> secondTreeList = new ArrayList<>();
        List<HisRegionModel> thirdTreeList = new ArrayList<>();

        for (HisRegionModel city : cityList) {
            String codeTmp1 = String.valueOf(city.getRegionCode());
            String codeTmp2 = codeTmp1.substring(2, 4);
            String codeTmp3 = codeTmp1.substring(4, 6);
            //找到根节点。
            if ("00".equals(codeTmp2) && "00".equals(codeTmp3)) {
                HisRegionModel baseTree = new HisRegionModel();
                baseTree.setRegionCode(city.getRegionCode());
                baseTree.setTitle(city.getTitle());
                baseTree.setId(city.getId());
                baseTreeList.add(baseTree);
                //找到二级节点
            } else if ("00".equals(codeTmp3)) {
                HisRegionModel secondTree = new HisRegionModel();
                secondTree.setRegionCode(city.getRegionCode());
                secondTree.setTitle(city.getTitle());
                secondTree.setId(city.getId());
                secondTreeList.add(secondTree);
                //剩下的是三级节点
            } else {
                HisRegionModel thirdTree = new HisRegionModel();
                thirdTree.setRegionCode(city.getRegionCode());
                thirdTree.setTitle(city.getTitle());
                thirdTree.setId(city.getId());
                thirdTreeList.add(thirdTree);
            }
        }
        //遍历二级节点
        for (HisRegionModel secondTree : secondTreeList) {
            String str = String.valueOf(secondTree.getRegionCode());
            //获取二级节点前4位
            String secondTree0_4 = str.substring(0, 4);
            //遍历3级节点，找出前4位与2级节点相同的
            List<HisRegionModel> tempList = thirdTreeList.stream().filter(e -> String.valueOf(e.getRegionCode()).substring(0, 4).equals(secondTree0_4)).collect(Collectors.toList());
            //设置二级节点的三级节点
            secondTree.setChildren(tempList);
        }
        //遍历根节点
        for (HisRegionModel baseTree : baseTreeList) {
            String str = String.valueOf(baseTree.getRegionCode());
            //获取根节点的前两位
            String baseTree0_2 = str.substring(0, 2);
            //遍历2级节点，找出前两位与根节点相同的
            List<HisRegionModel> tempList = secondTreeList.stream().filter(e -> String.valueOf(e.getRegionCode()).substring(0, 2).equals(baseTree0_2)).collect(Collectors.toList());
            //设置根节点的二级节点
            baseTree.setChildren(tempList);
        }
        return R.ok(baseTreeList);
    }

    @Override
    public R<?> queryById(String id) {
        HisRegion appRegion = this.getById(id);
        if (appRegion == null) {
            return R.error(500,"未找到对应数据");
        }
        return R.ok(appRegion);
    }


}

